<?php

/* 加上全返的功能 */
class GloballwnCashbacklevel
{

    public $orderdb;

    public $order;

    public $site_id;

    public $userlist;

    public $member_id;

    public $member;

    public $sale;

    public $saledb;

    public $memberdb;

    public $Affdb;

    public $affsetting;

    public $supplier;

    public $product;

    public $connect_db;

    public $error = array();

    public $sup_member_id;
 // 供应商的member_id
                           
    // 构造函数
    public function GloballwnCashbacklevel($order_id = 0, $site_id = 0, $member_id = 0)
    
    {
        import("@.ORG.Cashback.Cashback");
        
        $this->getthisdata($order_id, $site_id);
        
        $this->member = $member_id > 0 ? $this->UserInfo($member_id) : $this->order['member_id'];
        
        if (! $this->order) {
            
            $this->error['info'] = '订单不存在！';
        }
        
        $db = M('Affiliatesetting');
        
        $affsetting = $db->where(array(
            'site_id' => $this->site_id,
            'classname' => 'GloballwnCashbacklevel'
        ))->find();
        
        $this->affsettingarr = unserialize($affsetting['value']);
        
        // dump($this->member);
        
        // exit(dump($this->userlist));
        
        $points_db = M('Points');
        $pointslog_db = M('Points_log');
        
        foreach ($this->sale as $k => $v) {
           
            if ($v['product_id'] == $this->affsettingarr['levelbuy'][0]) {
                
                $this->updateUserLevel();
            }
			
            if ($this->order['confirm'] == 1) {
				
                $inte_data = $this->integral($v);
				
                $platform_data['member_id'] = 0;
                $platform_data['remark'] = $inte_data['platform']['remark'];
				$platform_data['form_name'] = $this->member['nickname'];
                $platform_data['total'] = $inte_data['platform']['total'];
                $platform_data['sale_id'] = $v['id'];
				$platform_data['order_id'] = $this->order['id'];
                $platform_data['time'] = time();
                $platform_data['form'] = $this->member_id;
				$member=$this->UserInfo($platform_data['member_id']);
				$platform_data['member_name'] = $member['nickname'];
                if ($pointslog_db->add($platform_data)) {
                    $points_db->add($platform_data);
                }
                
                $shop_data['member_id'] = 0;
				$shop_data['form_name'] = $this->member['nickname'];
                $shop_data['remark'] = $inte_data['platform']['remark'];
                $shop_data['total'] = $inte_data['platform']['total'];
                $shop_data['time'] = time();
				$shop_data['order_id'] = $this->order['id'];
                $shop_data['sale_id'] = $v['id'];
                $shop_data['form'] = $this->member_id;
				$member=$this->UserInfo($shop_data['member_id']);
				$shop_data['member_name'] = $member['nickname'];
                if ($pointslog_db->add($shop_data)) {
                    $points_db->add($shop_data);
                }
				
				if($this->order['integral_pay']<0){
                $consumer_data['member_id'] = 0;
                $consumer_data['remark'] = $inte_data['platform']['remark'];
                $consumer_data['total'] = $inte_data['platform']['total'];
				$consumer_data['form_name'] = $this->member['nickname'];
                $consumer_data['time'] = time();
                $consumer_data['sale_id'] = $v['id'];
				$consumer_data['order_id'] = $this->order['id'];
                $consumer_data['form'] = $this->member_id;
				$member=$this->UserInfo($consumer_data['member_id']);
				$consumer_data['member_name'] = $member['nickname'];
                if ($pointslog_db->add($consumer_data)) {
                    $points_db->add($consumer_data);
                }
				}
            }
        }
    }

    public function integral($data)
    {
        if ($data['type'] == 1) {
            $percentage = 16;
        } elseif ($data['type'] == 2) {
            $percentage = 8;
        }
        $info['platform']['total'] = floot($data['total'] * ($percentage / 100), 2);
        $info['platform']['remark'] = '用户' . $data['member_id'] . ',下单' . $data['id'] . '，手续费' . $info['platform']['total'];
        $info['shop']['total'] = $data['total'] - $platform;
        $info['shop']['inte'] = $platform * 1.5;
        $info['consumer']['total'] = $data['total'] * (0.9);
        $info['consumer']['inte'] = $consumer['total'] * 0.7;
        $info['shop']['remark'] = '用户' . $data['member_id'] . ',下单' . $data['id'] . '，获得积分' . $info['shop']['inte'];
        $info['consumer']['remark'] = '下单' . $data['id'] . '，获得积分' . $info['consumer']['inte'];
        return $info;
    }
    
    // 创建设置项表单
    public function createform()
    
    {
        
        // $ret = array ('levelname' => array ( 0 => '股东商', 1 => '渠道商', 2 => '代理商', 3 => '分销商', ), 'levelbuy' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff_' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'rlevel' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ),'level' => array ( 0,0,0,0,0,0,0,0 ),'levelnamebase' => 'VIP会员', 'changelevel' => '恭喜您升级成为：@levelname@');
        $ret = $this->Affdb->where(array(
            
            'site_id' => $this->site_id,
            
            'classname' => 'GloballwnCashbacklevel'
        ))->find();
        
        $ret = unserialize($ret['value']);
        
        // F('ret',$ret);
        
        $html = '<style>#RangeCashbacklevel td{padding:5px;}</style>
		<style>
		body{ background-color:#5da9c0}
		 table{ background-color:#639d75;border:1px solid #79304e}
		 input{ background-color:#b7d2b3 }
		 </style>
		<table    id="RangeCashbacklevel"  border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
	<th align="center" style="text-align:center;">级别名称</th>
	<th align="center" style="text-align:center;">直接下级</th>
  </tr>
  <tr>
    <td align="center" valign="middle">1</td>
	<td align="center" valign="middle">《消费者》&nbsp;&nbsp;<input type="text" name="levelname[]" value="' . $ret['levelname'][0] . '" /></td>
<td align="center" valign="middle"></td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
	<td align="center" valign="middle"> 《 商 家 》&nbsp;&nbsp;<input type="text" name="levelname[]" value="' . $ret['levelname'][1] . '" /></td>
	<td></td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
	<td align="center" valign="middle">《市代理》&nbsp;&nbsp;<input type="text" name="levelname[]" value="' . $ret['levelname'][2] . '" /></td>
<td></td>
  </tr>
   <tr>
    <td align="center" valign="middle">4</td>
	<td align="center" valign="middle">《省代理》&nbsp;&nbsp;<input type="text" name="levelname[]" value="' . $ret['levelname'][3] . '" /></td>
<td></td>
 </tr>
   <tr>
    <td align="center" valign="middle">5</td>
	<td align="center" valign="middle">《区代理》&nbsp;&nbsp;<input type="text" name="levelname[]" value="' . $ret['levelname'][4] . '" /></td>
<td></td>
  </tr>
<tr>
    <td align="center" valign="middle">6</td>
	<td align="center" valign="middle">《服务商》&nbsp;&nbsp;<input type="text" name="levelname[6]" value="' . $ret['levelname'][6] . '" /></td>
<td align="center" valign="middle">《业务员》<input type="text" name="levelname[5]" value="' . $ret['levelname'][5] . '" /></td>
  </tr>
</table>
<br>
<table cellpadding="0" class="Threelevel" cellspacing="0" border="1" width="100%">
    <td align="center" valign="middle" style="width:150px;">会员升级后通知信息</td>
    <td align="left" colspan="2"><input style="width:100%" type="text" name="changelevel" value="' . $ret['changelevel'] . '" /><br>
等级名称@levelname@
</td>
  </tr>
</table>
<style>.Threelevel td{padding:5px;}</style>
<div style="margin-top:35px;">
<table class="Threelevel" border="1" cellspacing="0" style=" float: left;" cellpadding="5" width="40%">
  <tr>
    <th align="center" style="text-align:center;  width:100px;" colspan="2">消费者</th>
  </tr>
    <tr>
  <th align="center" style="text-align:center; width:100px;">一级</th>
	<th align="center" style="text-align:center; width:100px;">二级</th>
  </tr>
  <tr>
    <td align="center"><input type="text" name="first[]" value="' . $ret['first'][0] . '" />%</td>
	<td align="center"><input type="text" name="second[]" value="' . $ret['second'][0] . '" />%</td>
  </tr>
</table>
<table class="Threelevel" border="1" cellspacing="0" style=" float: right;" cellpadding="5" width="40%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="2">商家</th>
  </tr>
  <tr>
  <th align="center" style="text-align:center; width:100px;">一级</th>
	<th align="center" style="text-align:center; width:100px;">二级</th>
  </tr>
  <tr>
    <td align="center"><input type="text" name="first[]" value="' . $ret['first'][1] . '" />%</td>
	<td align="center"><input type="text" name="second[]" value="' . $ret['second'][1] . '" />%</td>
  </tr>
</table>
</div>
<div style="margin-top:165px;">
<table class="Threelevel" border="1"  style=" float:left;" cellspacing="0" cellpadding="5" width="40%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="2">市代理</th>
  </tr>
  <tr>
  <tr>
<th align="center" style="text-align:center; width:100px;">16%系列</th>
	<th align="center" style="text-align:center; width:100px;">8%系列</th>
  </tr>
    <td align="center"><input type="text" name="first[]" value="' . $ret['first'][2] . '" />%</td>
	<td align="center"><input type="text" name="second[]" value="' . $ret['second'][2] . '" />%</td>
  </tr>
</table>
<table class="Threelevel" border="1"  style=" float: right;" cellspacing="0" cellpadding="5" width="40%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="2">省代理</th>
  </tr>
  <tr>
<th align="center" style="text-align:center; width:100px;">16%系列</th>
	<th align="center" style="text-align:center; width:100px;">8%系列</th>
  </tr>
   <tr>
    <td align="center"><input type="text" name="first[]" value="' . $ret['first'][3] . '" />%</td>
	<td align="center"><input type="text" name="second[]" value="' . $ret['second'][3] . '" />%</td>
  </tr>
</table>
</div>
<div style="margin-top:285px;">
<table class="Threelevel" border="1" cellspacing="0"  cellpadding="5" width="40%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="2">区代理</th>
  </tr>
    <tr>
<th align="center" style="text-align:center; width:100px;">16%系列</th>
	<th align="center" style="text-align:center; width:100px;">8%系列</th>
  </tr>
  <tr>
    <td align="center"><input type="text" name="first[]" value="' . $ret['first'][4] . '" />%</td>
	<td align="center"><input type="text" name="second[]" value="' . $ret['second'][4] . '" />%</td>
  </tr>
</table>
<div>
<br /><br />
<table class="Threelevel" border="1" cellspacing="0" cellpadding="5" width="70%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="4">服务商</th>
  </tr>
<tr>
  <th align="center" style="text-align:center; width:100px;" colspan="2">一级</th>
	<th align="center" style="text-align:center; width:100px;" colspan="2">二级</th>
</tr> 
  <tr>
    <td style="text-align:center;"rowspan="2" >业务员：</td><td align="center" rowspan="2" ><input type="text" name="first[]" value="' . $ret['first'][5] . '" />%</td>
	<td style="text-align:center;" rowspan="3" >直推服务商个数：</td><td align="center"> 《 1 - 9 个 》<input type="text" name="second[]" value="' . $ret['second'][5] . '" />%</td>
  </tr>
  <tr>
	<td align="center">《10-29个》<input type="text" name="second[]" value="' . $ret['second'][6] . '" />%</td>
  </tr>
  <tr>
 <td style="text-align:center;" >直推服务商：</td><td align="center" rowspan="3" ><input type="text" name="first[]" value="' . $ret['first'][6] . '" />%</td>
	<td align="center">《30以上》<input type="text" name="second[]" value="' . $ret['second'][7] . '" />%</td>
  </tr>
</table> 


<br /><br />
<table class="Threelevel" border="1" cellspacing="0" cellpadding="5" width="70%">
  <tr>
    <th align="center" style="text-align:center; width:100px;" colspan="4">升级商品</th>
  </tr>
<tr><td align="center" colspan="2">升级服务商购买商品id<input type="text" name="levelbuy[]" value="' . $ret['levelbuy'][0] . '" /></td></tr>
<tr>

  <th align="center" style="text-align:center; width:100px;" >一级服务商</th>
	<th align="center" style="text-align:center; width:100px;" >二级服务商</th>
</tr> 
  <tr>
    
	
  </tr>

  <tr>
 <td align="center" rowspan="3" ><input type="text" name="levelbuyfirst[]" value="' . $ret['levelbuyfirst'][0] . '" />%</td>
	<td align="center"><input type="text" name="levelbuysecond[]" value="' . $ret['levelbuysecond'][0] . '" />%</td>
  </tr>
</table> 

';
        
        return $html;
    }
    
    // 保存设置项
    public function saveform()
    
    {
        if (isset($_POST['first'])) {
            
            $data['classname'] = 'GloballwnCashbacklevel';
            
            $data['value'] = serialize($_POST);
            
            $data['site_id'] = $this->site_id;
            
            $ret = $this->Affdb->where(array(
                
                'site_id' => $data['site_id'],
                
                'classname' => $data['classname']
            ))->find();
            
            if ($ret) {
                
                $saveret = $this->Affdb->where(array(
                    
                    'site_id' => $data['site_id'],
                    
                    'classname' => $data['classname']
                ))
                    ->data(array(
                    
                    'value' => $data['value']
                ))
                    ->save();
            } else {
                
                $saveret = $this->Affdb->data($data)->add();
            }
            
            if ($saveret) {
                
                return true;
            } else {
                
                $this->error['info'] = $this->Affdb->getLastSql();
                
                return false;
            }
        }
    }

    public function get_Supplier_lower($id)
    {
        // exit(dump($id));
        return M('Member_connect')->where('member_id like "' . $id . '"')->count('id');
    }
    
    // 分销商和用户直接的等级
    public function getLevel($mid)
    {
        if (isset($mid)) {
            $res = M('Member_connect')->where('member_id = ' . $mid)->find();
            return $res['type'];
        } else {
            return 0;
        }
    }
    
    // 获取分销商的分成金额
    public function levelCash($data, $deep)
    
    {
        if ($deep == 1) {
            
            $proportion = 'first';
        } else 
            if ($deep == 2) {
                
                $proportion = 'second';
            }
        
        if ($data['level'] == 6 && $deep == 2) {
            $re = $this->connect_db->where('member_id = ' . $data['id'])->find();
            $count = $this->get_Supplier_lower($re['referee_id']);
            
            if ($count < 10) {
                $data['level'] = 5;
            }
            if ($count > 10 && $count < 30) {
                $data['level'] = 6;
            }
            if ($count > 30) {
                $data['level'] = 7;
            }
        }
        // dump($this->affsettingarr[$proportion][$data['level']]);
        
        // exit(dump($this->affsettingarr[$proportion][$level['type']]));
        return $this->affsettingarr[$proportion][$data['level']];
    }

    public function product_supplier($id)
    {
        $product = M('Product')->where('id =' . $id)->find();
        
        if ($product['supplier_id'] > 0) {
            $supplier = M('Supplier')->where('id = ' . $product['supplier_id'])->find();
            
            if ($supplier['member_id'] > 0) {
                // exit(dump($supplier['member_id']));
                return $supplier['member_id'];
                exit();
            }
        }
        
        return false;
    }
    
    // 获得父ID
    public function getPid($pid = 0, $arr = array(), $deep = 1, $data = NULL)
    {
        if ($data == $this->affsettingarr['levelbuy'][0]) {
            
            if ($deep == 3) {
                return $arr;
            }
            if ($pid == 0) {
                foreach ($this->order as $k => $v) {
                    if ($v['aff_id'] > 0) {
                        $pid = $v['aff_id'];
                    } else {
                        $pid = $this->member_id;
                    }
                }
            }
            $re = $this->connect_db->where('referee_id = ' . $pid)->find();
            if (! $re) {
                return $arr;
            }
            
            $re['deep'] = $deep;
            
            $arr[] = $re;
            $deep ++;
            return $this->getPid($re['member_id'], $arr, $deep, $data);
        }
        
        if ($pid == 0 && $deep == 1) {
            
            $pid = $this->member_id;
            $re = $this->memberdb->where('id = ' . $pid)->find();
            $arr = array();
            if ($re['pid'] > 0) {
                $re = $this->memberdb->where('id = ' . $re['pid'])->find();
                $re['deep'] = 1;
                $arr[] = $re;
                if ($re['pid'] > 0) {
                    $re = $this->memberdb->where('id = ' . $re['pid'])->find();
                    $re['deep'] = 2;
                    $arr[] = $re;
                }
            }
            
            return $this->getPid(0, $arr, 3, $data);
        }
        // dump($pid);
        if ($deep == 3) {
            
            if ($data > 0 && $pid == 0) {
                $supplier = $this->product_supplier($data);
                if ($supplier) {
                    $re = $this->connect_db->where('referee_id = ' . $supplier)->find();
                }
            }
            
            if ($pid > 0) {
                $re = $this->connect_db->where('referee_id = ' . $pid)->find();
            }
            if (! $re) {
                return $arr;
            }
            $re['deep'] = 3;
            $arr[] = $re;
            if ($re['type'] == 6) {
                
                $deep = 4;
            }
            return $this->getPid($re['member_id'], $arr, $deep, $data);
        }
        
        if ($deep == 4) {
            
            $re = $this->connect_db->where('referee_id = ' . $pid)->find();
            if (! $re) {
                return $arr;
            }
            $re['deep'] = 4;
            $arr[] = $re;
        }
        
        return $arr;
    }

    public function getError()
    
    {
        return $this->error['info'];
    }
    
    // 订单的总额
    public function getmoney()
    
    {
        
        // dump(M('Member')->where('id = 226709')->count('id'));
        return $this->saledb->where(array(
            
            'order_id' => $this->order['id']
        ))->select();
    }
    
    // 分给用户的金额
    public function getUser($user = array())
    {
        
        // exit(dump($user));
        $memberInfo = $this->UserInfo();
        $num = - 1;
        foreach ($this->sale as $k => $v) {
            
            $num ++;
            if ($v['product_id'] == $this->affsettingarr['levelbuy'][0]) {
                
                $list = $this->getPid(0, array(), 1, $v['product_id']);
                foreach ($list as $uk => $uv) {
                    
                    $m = $this->UserInfo($uv['member_id']);
                    if ($tag > 0) {
                        continue;
                    }
                    
                    if ($m['level'] != 6) {
                        $m['get_money'] = 0;
                    }
                    
                    if ($m['level'] == 6) {
                        
                        if ($uv['deep'] == 1) {
                            $proportion = 'levelbuyfirst';
                        } else 
                            if ($uv['deep'] == 2) {
                                $proportion = 'levelbuysecond';
                            }
                    } else {
                        $tag = 1;
                        continue;
                    }
                    
                    $m['get_money'] = round($v['total'] * ($this->affsettingarr[$proportion][0] / 100), 2);
                    $m['remark'] = '【' . $memberInfo['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $m['get_money'] . '。升级商品分润，收益等级为' . $this->affsettingarr['levelname'][$m['level']] . '的第' . ($uv['deep']) . '级';
                    $m['model'] = 2;
                    $m['deep'] = $uv['deep'];
                    $user[$uk] = $m;
                    // dump($m);
                }
                // exit(dump($user));
                return $user;
            }
            
            $tag = 0;
            
            foreach ($user[$num] as $uk => $uv) {
                if ($uv['type'] == NULL) {
                    if ($tag > 0) {
                        $uv['level'] = 0;
                    }
                    if ($uv['level'] != 1) {
                        $uv['level'] = 0;
                    } else {
                        $tag = 1;
                    }
                    
                    if ($uv['member_id'] == $this->member_id) {
                        continue;
                    }
                    
                    if ($uv['deep'] == 1) {
                        $proportion = 'first';
                    } else 
                        if ($uv['deep'] == 2) {
                            $proportion = 'second';
                        }
                    // if($uv['deep']==0){}
                    $user[$num][$uk]['get_money'] = round($v['total'] * ($this->affsettingarr[$proportion][$uv['level']] / 100), 2);
                    $user[$num][$uk]['remark'] = '【' . $memberInfo['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $user[$num][$uk]['get_money'] . '。分销收益等级为' . $this->affsettingarr['levelname'][$uv['level']] . '的第' . ($uv['deep']) . '级';
                    $user[$num][$uk]['model'] = 1;
                }
                
                if ($uv['type'] != null) {
                    $member = $this->UserInfo($uv['member_id']);
                    $member['deep'] = $uv['deep'] - 2;
                    
                    if ($member['level'] > 2) {
                        $user[$num][$uk]['get_money'] = 0;
                    }
                    if ($member['level'] == 6) {
                        $user[$num][$uk] = $member;
                        
                        $user[$num][$uk]['get_money'] = round($v['total'] * ($this->levelCash($member, $uv['deep'] - 2) / 100), 2);
                        $user[$num][$uk]['remark'] = '【' . $memberInfo['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $user[$num][$uk]['get_money'] . '。分润收益等级为' . $this->affsettingarr['levelname'][$member['level']] . '的第' . ($uv['deep'] - 2) . '级';
                        $user[$num][$uk]['model'] = '2';
                        continue;
                    }
                    if ($member['level'] > 1 && $member['level'] < 5) {
                        $user[$num][$uk] = $member;
                        $product = M('Product')->where('id = ' . $v['product_id'])->find();
                        if ($product['RebateModel'] == 0) {
                            continue;
                        }
                        if ($product['RebateModel'] == 1) {
                            $proportion = first;
                            $a = '百分之八模式';
                        }
                        if ($product['RebateModel'] == 2) {
                            $proportion = second;
                            $a = '百分之十六模式';
                        }
                        $user[$num][$uk]['get_money'] = round($v['total'] * ($this->affsettingarr[$proportion][$member['level']] / 100), 2);
                        $user[$num][$uk]['remark'] = '【' . $memberInfo['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $user[$num][$uk]['get_money'] . '。分润收益等级为' . $this->affsettingarr['levelname'][$member['level']] . '的' . $a;
                        $user[$num][$uk]['model'] = '2';
                        continue;
                    }
                    
                    $user[$num][$uk] = $member;
                    $user[$num][$uk]['get_money'] = round($v['total'] * ($this->affsettingarr[$proportion][$member['level']] / 100), 2);
                    $user[$num][$uk]['remark'] = '【' . $memberInfo['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $user[$num][$uk]['get_money'] . '。分润收益等级为' . $this->affsettingarr['levelname'][$member['level']] . '的第' . ($uv['deep'] - 2) . '级';
                    $user[$num][$uk]['model'] = '2';
                }
            }
        }
        // exit(dump($user));
        return $user;
    }

    public function Turnover($id, $total)
    {
        
        // exit(dump($this->order));
        $shop_db = M('Shop_turnover');
        $time = date('Y-m-d', time());
        $shop_data = $shop_db->where('shop_id = ' . $id . ' and date like "' . $time . '"')->find();
        // $this->order['id']=0;
        $updata['count'] = $shop_data == null ? 1 : $shop_data['count'] + 1;
        $updata['total'] = $shop_data == null ? $total : $shop_data['total'] + $total;
        // exit(dump($shop_db->where('id = ' . $id.' and date like "'.$time.'"')));
        if ($shop_data) {
            // echo 1;
            
            $turnover = $shop_db->where('shop_id = ' . $id . ' and date like "' . $time . '"')
                ->data($updata)
                ->save();
            
            return M('shop_turnover_log')->add(array(
                'turnover_id' => $turnover,
                'order_id' => $this->order['id'],
                'date' => $time
            ));
        }
        // echo 1;
        $updata['shop_id'] = $id;
        $updata['date'] = $time;
        $turnover = $shop_db->where('shop_id = ' . $id)
            ->data($updata)
            ->add();
        
        return M('shop_turnover_log')->add(array(
            'turnover_id' => $turnover,
            'order_id' => $this->order['id'],
            'date' => $time
        ));
        exit();
    }

    public function updateUserlevel($m_id)
    
    {
        if ($this->order['confirm'] == 0) {
            return false;
        }
        
        $member_db = D('Member');
        $user = $this->UserInfo();
        // $data['level']='6';
        foreach ($this->sale as $skey => $sval) {
            
            foreach ($this->affsettingarr['levelbuy'] as $key => $val) {
                
                if ($sval['product_id'] == $val) {
                    
                    // $data['product_id']=$val;
                    // $this->insertlog();
                    $data['id'] = $this->order['member_id'];
                    $data['level'] = 6;
                    
                    $res = 1;
                }
            }
        }
        // $this->insertlog();
        if ($res != 0 && $user['level'] < $data['level']) {
            
            $res = $member_db->changeLevel($data);
            // dump($data);
            $mtmdb = M('Member_member');
            unset($data['id']);
            $mtmdb->where(array(
                
                'site_id' => __SITEID__,
                
                'smember_id' => $user['id']
            ))
                ->data($data)
                ->save();
            
            sendWXMsg($memberInfo['openid'], str_replace('@levelname@', $this->getLevelName(), $this->affsettingarr['changelevel']));
        } else {
            
            return false;
        }
    }

    public function getLevelName()
    
    {
        foreach ($this->affsettingarr['levelname'] as $key => $val) {
            if ($key == $this->member['level']) {
                
                $name = $val;
            }
        }
        
        return $name;
    }

    public function UserInfo($id = 0)
    
    {
        if ($id == 0) {
            
            $id = ' and id = ' . $this->member_id;
        } else {
            
            $id = ' and id = ' . $id;
        }
        
        return M('Member')->where('site_id = ' . __SITEID__ . ' ' . $id)->find();
    }

    public function getInsertData($user, $shop)
    
    {
        $data['deep'] = $user['deep'];
        
        $data['affmoney'] = $this->sale[0]['aff_money'];
        
        $data['type'] = 0;
        
        $data['member_id'] = $user['id'];
        
        $data['user_id'] = 0;
        
        $data['pdstate'] = 3; // 类型3为分成
        
        /*
         *
         * if($user['aff__'] > 0){
         *
         *
         *
         * //未确认分成
         *
         *
         *
         * $data['pdstate'] = 100;
         *
         *
         *
         * }
         *
         */
        if (! is_array($this->member)) {
            $this->member = $this->UserInfo($this->member);
        }
        $data['from_member'] = 0;
        if ($shop > 0) {
            $data['from_member'] = $shop;
        }
        $data['dateline'] = time();
        
        $data['changenum'] = $user['get_money'];
        
        $data['order_id'] = $this->order['id'];
        
        $data['order_sn'] = $this->order['ordernumber'];
        
        $data['product_id'] = $this->sale[0]['product_id'];
        
        $data['num'] = $this->sale[0]['num'];
        $data['buy'] = 1;
        if ($sv['product_id'] == $this->affsettingarr['levelbuy']['0']) {
            $data['buy'] = 2;
        }
        $data['types'] = 1;
        if ($user['model'] == 2) {
            $data['types'] = 2;
        }
        
        $data['site_id'] = $this->site_id;
        
        $data['attr'] = $this->sale[0]['attr'];
        
        $data['remark'] = $user['remark'];
        
        $data['goodsMoney'] = $this->sale[0]['total'];
        
        return $data;
    }

    public function Sendwechat($user)
    
    {
        $domain = C('DOMAIN_MAIN');
        
        $picurl = 'http://' . $domain[0] . '/Public' . M('Product')->where(array(
            
            'id' => $this->sale[0]['product_id']
        ))->getField('img_url');
        
        if ($this->sale[0]['pay_status'] == 1) {
            
            $sendWXNews[0]['title'] = '订单支付通知';
            
            $sendWXNews[0]['url'] = '';
            
            $sendWXNews[0]['picurl'] = $picurl;
            
            $sendWXNews[0]['description'] = '【' . $this->member['nickname'] . '】支付，订单号为：' . $this->order['ordernumber'] . '，收益金额为：' . $user['getMoney'];
            
            // $msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
            
            sendWXNews($user['openid'], $sendWXNews);
        } else 
            
            if ($this->sale[0]['pay_status'] == 0) {
                
                $sendWXNews[0]['title'] = '会员下单通知';
                
                $sendWXNews[0]['url'] = '';
                
                $sendWXNews[0]['picurl'] = $picurl;
                
                $sendWXNews[0]['description'] = '【' . $this->member['nickname'] . '】下单，订单号为：' . $this->order['ordernumber'] . '，会员付款后您将得到收益金额为：' . $user['getMoney'];
                
                sendWXNews($user['openid'], $sendWXNews);
            }
    }

    public function insertlog()
    
    {
        $db = M('Affiliatelog');
        
        $db->where(array(
            
            'order_id' => $this->order['id']
        ))->delete();
        
        $db = M('Member_account_log');
        
        /*
         *
         * $map['type'] = 0;
         *
         *
         *
         * $map['member_id'] = $user['id'];
         *
         *
         *
         * $map['order_id'] = $this->order['id'];
         *
         *
         *
         * $map['product_id'] = $this->sale['product_id'];
         *
         *
         *
         * $map['attr'] = $sale['attr'];
         *
         *
         *
         * if($db -> where($map) -> find()){
         *
         *
         *
         * continue;
         *
         *
         *
         * }
         *
         */
        
        $this->getAffData();
        
        $num = - 1;
        foreach ($this->sale as $k => $v) {
            $num ++;
            $tag = 0;
            if ($v['product_id'] == $this->affsettingarr['levelbuy'][0]) {
                foreach ($this->userlist as $key => $val) {
                    if (! $val['remark']) {
                        continue;
                    }
                    
                    if ($val['get_money'] < 0) {
                        continue;
                    }
                    if ($val['level'] != 6) {
                        continue;
                    }
                    $data = $this->getInsertData($val);
                    // exit(dump($val));
                    // exit(dump($data));
                    
                    $db->data($data)->add();
                }
                continue;
            }
            
            if ($v['product_id'] != $this->affsettingarr['levelbuy'][0]) {
                $pid = $this->product_supplier($v['product_id']);
                foreach ($this->userlist[$num] as $key => $val) {
                    if ($val['get_money'] < 0) {
                        continue;
                    }
                    // exit(dump($v));
                    
                    // echo 1;
                    
                    if ($tag == 0) {
                        if ($pid) {
                            
                            $this->Turnover($pid, $v['price']);
                            
                            $tag ++;
                        }
                    }
                    $data = $this->getInsertData($val, $pid);
                    // exit(dump($data));
                    if ($data['changenum'] > 0) {
                        
                        $db->data($data)->add();
                    }
                }
            }
        }
        // exit();
        // exit();
        // 信息通知
        // exit();
        $this->Sendwechat($user);
        
        // $msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
        
        // sendWXNews($v['openid'], $sendWXNews);
    }
    
    // 获取等级名称列表
    public function getLevelNameList()
    
    {
        $memberInfo = $this->memberdb->where(array(
            
            'id' => $this->member_id['id']
        ))->find();
        
        $namelist = $this->affsettingarr['levelname'];
        
        // $namelist = array_reverse($namelist);
        
        return $namelist;
    }

    public function getthisdata($order_id, $site_id)
    
    {
        $this->memberdb = D('Member');
        
        $this->orderdb = D('Order');
        
        $this->saledb = M('Sale');
        $this->connect_db = M('Member_connect');
        
        $this->site_id = $site_id;
        
        $this->Affdb = M('affiliatesetting');
        
        $affsetting = $this->Affdb->where(array(
            
            'site_id' => $this->site_id,
            
            'classname' => 'GloballwnCashbacklevel'
        ))->find();
        
        $this->affsettingarr = unserialize($affsetting['value']);
        
        if ($order_id > 0) {
            
            $this->order = $this->orderdb->where(array(
                
                'id' => $order_id
            ))->find();
            
            $this->member_id = $member_id > 0 ? $member_id : $this->order['member_id'];
            
            $this->sale = $this->getmoney();
            $num = - 1;
            // dump($this->sale);
            
            foreach ($this->sale as $k => $v) {
                $num ++;
                $this->userlist[$num] = $this->getPid(0, $this->userlist[$num], 1, $v['product_id']);
                // dump($this->product_supplier($v['product_id']));
            }
            
            // exit(dump($this->userlist));
            
            $this->userlist = $this->getUser($this->userlist);
            
            $this->member = $this->getUser($this->member_id);
        }
    }
    
    // 下单提醒（当前未付款）
    public function sendMsg()
    
    {
        $this->getthisdata($order_id);
        $num = - 1;
        foreach ($this->sale as $k => $v) {
            $num ++;
            $shop = $this->product_supplier($v['product_id']);
            foreach ($this->userlist[$num] as $key => $val) {
                
                if ($val['get_money'] <= 0) {
                    
                    continue;
                }
                
                $this->remind($val, $shop);
            }
        }
    }

    public function remind($user, $shop)
    
    {
        /*
         * $thismember = $this->memberdb->where(array(
         *
         * 'id' => $this->member_id
         * ))->find();
         */
        $db = M('Affiliatelog');
        
        // 写入日志，以便以后统计，注意这里不是写账户日志
        
        $map['type'] = 1;
        
        $map['member_id'] = (int) $user['id'];
        
        $map['order_id'] = $this->order['id'];
        
        foreach ($this->sale as $key => $val) {
            
            $map['product_id'] = $val['product_id'];
            
            if ($db->where($map)->find()) {
                
                continue;
            }
            
            $data['site_id'] = $this->order['site_id'];
            
            $data['member_id'] = (int) $user['id'];
            
            $data['datetime'] = time();
            
            $data['type'] = 1;
            
            $data['order_id'] = $this->order['id'];
            $data['from_member'] = 0;
            if ($shop > 0) {
                $data['from_member'] = $shop;
            }
            $data['aff_money'] = $user['get_money'];
            $data['types'] = 1;
            // echo 2;
            // dump($user);
            if ($user['model'] == 2) {
                echo 1;
                $data['types'] = 2;
            }
            $data['product_id'] = $val['product_id'];
            // exit(dump($this->userlist));
            if ($data['aff_money'] > 0) {
                
                $money += $data['aff_money'];
                
                $res = $db->data($data)->add();
            }
        }
        
        $this->Sendwechat($user);
        // exit(dump($res));
        // sendWXNews($v['openid'], $sendWXNews);
    }

    public function getAffData()
    
    {
        $db = M('Member_account_log');
        
        $levelname = $this->getLevelName();
        
        $level = M('Member')->where(array(
            
            'id' => $this->member_id
        ))->getField('level');
        
        // if(isset($_GET['dump'])){echo $level;dump($this->member_id);}
        
        $ret = array();
        
        $data = $db->where(array(
            
            'member_id' => $this->member_id,
            
            'site_id' => $this->site_id,
            
            'type' => 1,
            
            'pdstate' => 3,
            
            'order_id' => array(
                
                'gt',
                
                0
            )
        ))
            ->Field('count(*) as orderCount, sum(changenum) as orderAffMoney, sum(goodsMoney) as orderTotal')
            ->select();
        
        // dump($db -> getLastSql());
        
        $ret[0]['levelname'] = $levelname;
        
        // 级差订单数量
        
        $ret[0]['orderCount'] = (int) $data[0]['orderCount'];
        
        // 级差订单总额
        
        $ret[0]['orderTotal'] = (float) $data[0]['orderTotal'];
        
        // 级差订单分成
        
        $ret[0]['orderAffMoney'] = (float) $data[0]['orderAffMoney'];
        
        $ret[0]['type'] = 1;
        
        return $ret;
    }
}